const fs = require('fs');
const sqlite3 = require('sqlite3').verbose();


const
    query = (word, isZN) => {
        return new Promise((resolve, reject) => {
            let sql = `SELECT * FROM stardict s WHERE s.word = '${word}'`;
            let zsql = `SELECT * FROM stardict s WHERE s.translation LIKE '%n. ${word},%' 
                OR s.translation LIKE '%, ${word},%' 
                OR s.translation LIKE '%,${word},%'
                OR s.translation LIKE '%, ${word}'
            `;

            sql = isZN ? zsql : sql;
            
            // 创建数据库对象
            let db = new sqlite3.Database('db/stardict.db');

            // 执行查询语句
            db.serialize(() => {
                db.each(sql, (err, row) => {
                    if (err) {
                        reject(err.message);
                    }

                    resolve(row); // 可根据实际需求处理结果
                });
            });

            // 关闭数据库连接
            db.close();
        })
    },
    printResult = (word, queryRes, isZN) => {
        let res = isZN ? queryRes.word : queryRes.translation;
        (res || '').replace('/\\n/g', '');
        let obj = {
            "查询": word,
            "结果": res,
            "音标": queryRes.phonetic,
            "解释": queryRes.definition,
        }
        console.log(obj);
        // console.table(obj);
    };


process.stdin.setEncoding('utf8');
console.log('**********************************');
console.log('--------^> EZ互译词典 <^----------');
console.log('**********************************');
console.log('请输入内容按[Enter]查询：');

// 监听用户输入事件
process.stdin.on('data', async(input) => {
    if(!fs.existsSync('db/stardict.db')){
        let msg = '词典数据库db/stardict.db不存在,请先下载！\r\n（下载链接: https://pan.baidu.com/s/11iQztUkWC9pV84OCdwVFkQ?pwd=6kus 提取码: 6kus）';
        console.log(msg);
        return;
    }

    let word = input.trim();
    let reg=/^[\u4E00-\u9FA5]+$/;
    let isZN = !reg.test(word) ? false : true;

    let res = await query(word, isZN);
    printResult(word, res, isZN);

    // 继续等待输入
    console.log('请输入内容按[Enter]查询：');
});
